'''
Author: tomwoo tom.woo@outlook.com
Date: 2025-08-07 20:15:07
LastEditors: tomwoo tom.woo@outlook.com
LastEditTime: 2025-08-08 20:06:10
FilePath: /Weather_Forecast_Agent/utils.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''

import sched
import time
from threading import Thread

def timeout_task(scheduler, timeout, priority, event_info, action, args=()):
    action(*args)

def interval_task(scheduler, interval, priority, event_info, action, args=()):
    action(*args)
    event = scheduler.enter(interval, priority, interval_task, (scheduler, interval, priority, event_info, action, args))
    event_info["event"] = event

def timing_task_thread_func(scheduler):
    scheduler.run(blocking=True) # 阻塞模式运行

def set_timing_task(timing_task, action, delay, args=()):
    event_info = {}

    # 初始化调度器（时间函数使用time.time，延迟函数使用time.sleep）
    scheduler = sched.scheduler(time.time, time.sleep)

    # 添加周期性任务（第1个参数为执行间隔秒数，第2个参数为优先级，第3个参数为执行的函数，第4个参数为函数的参数）
    event = scheduler.enter(delay, 1, timing_task, (scheduler, delay, 1, event_info, action, args))

    event_info["scheduler"] = scheduler
    event_info["event"] = event

    thread = Thread(target = timing_task_thread_func, args=(scheduler,), daemon=True)
    thread.start()

    return event_info

def clear_timing_task(event_info):
    event_info["scheduler"].cancel(event_info["event"])

def set_timeout(action, timeout: float, args=()): # timeout unit: second
    return set_timing_task(timeout_task, action, timeout, args)

def clear_timeout(event_info):
    clear_timing_task(event_info)

def set_interval(action, interval: float, args=()): # interval unit: second
    return set_timing_task(interval_task, action, interval, args)

def clear_interval(event_info):
    clear_timing_task(event_info)

# end of file
